package com.dc.java8._1_lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Java8 内置的四大核心函数式接口
 * 
 * 		Consumer<T> : 消费型接口
 * 				void accept(T t);
 *
 * 		Supplier<T> : 供给型接口
 * 				T get();
 *
 * 		Function<T, R> : 函数型接口
 * 				R apply(T t);
 *
 * 		Predicate<T> : 断言型接口
 * 				boolean test(T t);
 * 
 */
public class LambdaTest5 {
	
	/**
	 *  Consumer<T> : 消费型接口
	 *  void accept(T t);
	 */
	public void consumerUtil(String str,Consumer<String> con) {
		con.accept(str);
	}
	
	@Test
	public void test1() {
		consumerUtil("独孤", x -> System.out.println("你好，" + x));
	}


	/**
	 * 供给型接口
	 */
	public List<Integer> supplierUtil(int num,Supplier<Integer> sup){
		List<Integer> result = new ArrayList<>();
		for (int i = 0; i < num; i++) {
			result.add(sup.get());
		}
		return result;
	}

	@Test 
	public void test2() {
		List<Integer> list = supplierUtil(10, () -> (int) (Math.random() * 100));
		list.forEach(System.out::println);
	}



	/**
	 * 函数式接口
	 */
	public String functionUtil(String str,Function<String, String> fun) {
		return fun.apply(str);
	}

	@Test
	public void test3() {
		String str = functionUtil("\t\t\tabc  ", String::trim);
		System.out.println(str);
	}


	
	/**
	 * 断言型接口
	 */
	public List<String> predicateUtil(List<String> list,Predicate<String> pre){
		List<String> strList = new ArrayList<>();
		for (String str : list) {
			if (pre.test(str)) {
				strList.add(str);
			}
		}
		return strList;
	}
	
	@Test
	public void test4() {
		List<String> list = Arrays.asList("Hello", "atguigu", "Lambda", "www", "ok");
		List<String> strList = predicateUtil(list, s -> s.length() > 3);
		strList.forEach(System.out::println);
	}

}
